import express, { Request, Response } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { query } from '../database';
import { authenticateToken } from '../middleware/auth';
import { body, validationResult } from 'express-validator';

const router = express.Router();

// 获取所有资产
router.get('/', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { page = 1, limit = 10, category, status, search } = req.query;
    
    // 确保分页参数是有效的数字
    const pageNum = Math.max(1, parseInt(page as string) || 1);
    const limitNum = Math.max(1, parseInt(limit as string) || 10);
    const offset = (pageNum - 1) * limitNum;
    
    let whereClause = '1=1';
    const params: any[] = [];

    if (category) {
      whereClause += ' AND a.category = ?';
      params.push(category);
    }

    if (status) {
      whereClause += ' AND a.status = ?';
      params.push(status);
    }

    if (search) {
      whereClause += ' AND (a.name LIKE ? OR a.model LIKE ? OR a.serial_number LIKE ?)';
      const searchTerm = `%${search}%`;
      params.push(searchTerm, searchTerm, searchTerm);
    }

    // 获取总数
    const countResult = await query(`
      SELECT COUNT(*) as total 
      FROM assets a 
      WHERE ${whereClause}
    `, params);
    const total = (countResult as any[])[0].total;

    // 获取资产列表 - 使用字符串拼接LIMIT和OFFSET避免参数绑定问题
    console.log('Asset query params:', params, 'limitNum:', limitNum, 'offset:', offset);
    console.log('Asset WHERE clause:', whereClause);
    
    const assets = await query(`
      SELECT a.id, a.name, a.category, a.model, 
             a.serial_number as serialNumber,
             a.purchase_date as purchaseDate,
             a.price as purchasePrice,
             a.location, a.status,
             a.description, a.created_at as createdAt, a.updated_at as updatedAt,
             a.created_by
      FROM assets a
      WHERE ${whereClause}
      ORDER BY a.created_at DESC
      LIMIT ${limitNum} OFFSET ${offset}
    `, params);

    res.json({
      success: true,
      data: {
        assets,
        pagination: {
          current: pageNum,
          pageSize: limitNum,
          total: total,
          totalPages: Math.ceil(total / limitNum)
        }
      }
    });

  } catch (error) {
    console.error('获取资产列表失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 获取单个资产
router.get('/:id', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    const assets = await query(`
      SELECT a.id, a.name, a.category, a.model, 
             a.serial_number as serialNumber,
             a.purchase_date as purchaseDate,
             a.price as purchasePrice,
             a.location, a.status, a.assigned_to as assignedTo,
             a.description, a.created_at as createdAt, a.updated_at as updatedAt,
             u.username as created_by_name
      FROM assets a
      LEFT JOIN users u ON a.created_by = u.id
      WHERE a.id = ?
    `, [id]);

    if ((assets as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '资产不存在' 
      });
    }

    res.json({
      success: true,
      data: (assets as any[])[0]
    });

  } catch (error) {
    console.error('获取资产详情失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 创建资产
router.post('/', authenticateToken, [
  body('name').notEmpty().withMessage('资产名称不能为空'),
  body('category').notEmpty().withMessage('资产类别不能为空'),
  body('status').optional().isIn(['active', 'maintenance', 'retired', '正常', '维修中', '报废']).withMessage('状态值无效'),
  body('purchasePrice').optional().isNumeric().withMessage('价格必须是数字')
], async (req: Request, res: Response) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        success: false, 
        message: '输入验证失败', 
        errors: errors.array() 
      });
    }

    const {
      name,
      category,
      model,
      serialNumber,
      purchaseDate,
      purchasePrice,
      location,
      status = 'active',
      assignedTo,
      description
    } = req.body;

    const userId = (req as any).user.userId;
    const assetId = uuidv4();

    await query(`
      INSERT INTO assets (
        id, name, category, model, serial_number, 
        purchase_date, price, location, status, assigned_to, description, created_by
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `, [
      assetId, name, category, model, serialNumber,
      purchaseDate, purchasePrice, location, status, assignedTo, description, userId
    ]);

    res.status(201).json({
      success: true,
      message: '资产创建成功',
      data: { id: assetId }
    });

  } catch (error) {
    console.error('创建资产失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 更新资产
router.put('/:id', authenticateToken, [
  body('name').optional().notEmpty().withMessage('资产名称不能为空'),
  body('category').optional().notEmpty().withMessage('资产类别不能为空'),
  body('status').optional().isIn(['active', 'maintenance', 'retired', '正常', '维修中', '报废']).withMessage('状态值无效'),
  body('purchasePrice').optional().isNumeric().withMessage('价格必须是数字')
], async (req: Request, res: Response) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        success: false, 
        message: '输入验证失败', 
        errors: errors.array() 
      });
    }

    const { id } = req.params;
    const updateFields = req.body;

    // 检查资产是否存在
    const assets = await query('SELECT id FROM assets WHERE id = ?', [id]);
    if ((assets as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '资产不存在' 
      });
    }

    // 字段映射：前端字段名 -> 数据库字段名
    const fieldMapping: { [key: string]: string } = {
      'name': 'name',
      'category': 'category',
      'model': 'model',
      'serialNumber': 'serial_number',
      'purchaseDate': 'purchase_date',
      'purchasePrice': 'price',
      'location': 'location',
      'status': 'status',
      'assignedTo': 'assigned_to',
      'description': 'description'
    };

    // 构建更新SQL
    const allowedFields = Object.keys(fieldMapping);
    const fieldsToUpdate = Object.keys(updateFields).filter(field => allowedFields.includes(field));
    
    if (fieldsToUpdate.length === 0) {
      return res.status(400).json({ 
        success: false, 
        message: '没有有效的更新字段' 
      });
    }

    const setClause = fieldsToUpdate.map(field => `${fieldMapping[field]} = ?`).join(', ');
    const values = fieldsToUpdate.map(field => updateFields[field]);

    await query(`
      UPDATE assets 
      SET ${setClause}, updated_at = CURRENT_TIMESTAMP 
      WHERE id = ?
    `, [...values, id]);

    res.json({
      success: true,
      message: '资产更新成功'
    });

  } catch (error) {
    console.error('更新资产失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 删除资产
router.delete('/:id', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    // 检查资产是否存在
    const assets = await query('SELECT id FROM assets WHERE id = ?', [id]);
    if ((assets as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '资产不存在' 
      });
    }

    // 删除资产（相关的盘点记录会因为外键约束自动删除）
    await query('DELETE FROM assets WHERE id = ?', [id]);

    res.json({
      success: true,
      message: '资产删除成功'
    });

  } catch (error) {
    console.error('删除资产失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 获取资产统计信息
router.get('/stats/overview', authenticateToken, async (req: Request, res: Response) => {
  try {
    // 总资产数量
    const totalResult = await query('SELECT COUNT(*) as total FROM assets');
    const total = (totalResult as any[])[0].total;

    // 按状态统计
    const statusStats = await query(`
      SELECT status, COUNT(*) as count 
      FROM assets 
      GROUP BY status
    `);

    // 按类别统计
    const categoryStats = await query(`
      SELECT category, COUNT(*) as count 
      FROM assets 
      GROUP BY category 
      ORDER BY count DESC 
      LIMIT 10
    `);

    res.json({
      success: true,
      data: {
        total,
        statusStats,
        categoryStats
      }
    });

  } catch (error) {
    console.error('获取资产统计失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

export default router;
